import React, { useState } from 'react';
import { Upload, Save, X, Clock, Calendar, Settings, Code, AlertCircle } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { useNavigate } from 'react-router-dom';

const TaskCreate = ({ toggleSidebar }) => {
  const navigate = useNavigate();
  
  const [taskData, setTaskData] = useState({
    name: '',
    description: '',
    type: '',
    enabled: true,
    schedule: {
      type: 'cron', // cron, interval
      cronExpression: '',
      intervalValue: 1,
      intervalUnit: 'hours'
    },
    script: '',
    timeout: 300,
    retryCount: 3,
    notifyOnSuccess: false,
    notifyOnFailure: true,
    notifyEmail: ''
  });

  const taskTypes = [
    { value: 'backup', label: '数据备份' },
    { value: 'cleanup', label: '文件清理' },
    { value: 'report', label: '报告生成' },
    { value: 'monitor', label: '系统监控' },
    { value: 'notification', label: '通知发送' },
    { value: 'custom', label: '自定义脚本' }
  ];

  const cronPresets = [
    { value: '0 0 * * *', label: '每日午夜 (00:00)' },
    { value: '0 2 * * *', label: '每日凌晨2点' },
    { value: '0 9 * * 1-5', label: '工作日上午9点' },
    { value: '0 0 * * 0', label: '每周日午夜' },
    { value: '0 0 1 * *', label: '每月1日午夜' },
    { value: '*/5 * * * *', label: '每5分钟' },
    { value: '0 */2 * * *', label: '每2小时' }
  ];

  const intervalUnits = [
    { value: 'minutes', label: '分钟' },
    { value: 'hours', label: '小时' },
    { value: 'days', label: '天' }
  ];

  const handleSave = () => {
    // 验证表单
    if (!taskData.name.trim()) {
      alert('请输入任务名称');
      return;
    }
    
    if (!taskData.type) {
      alert('请选择任务类型');
      return;
    }

    if (taskData.schedule.type === 'cron' && !taskData.schedule.cronExpression) {
      alert('请设置执行计划');
      return;
    }

    // 这里应该调用API保存任务
    console.log('保存任务:', taskData);
    
    // 保存成功后跳转到任务列表
    navigate('/tasks/list');
  };

  const handleCancel = () => {
    navigate('/tasks/list');
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-xl flex items-center justify-center">
                  <Upload className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    创建定时任务
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    配置新的定时任务
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Button variant="outline" onClick={handleCancel}>
                <X className="w-4 h-4 mr-2" />
                取消
              </Button>
              <Button onClick={handleSave} className="bg-primary hover:bg-primary-600">
                <Save className="w-4 h-4 mr-2" />
                保存任务
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 左侧：基本信息 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 基本信息 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Settings className="w-5 h-5" />
                  <span>基本信息</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="name">任务名称 *</Label>
                  <Input
                    id="name"
                    value={taskData.name}
                    onChange={(e) => setTaskData(prev => ({ ...prev, name: e.target.value }))}
                    placeholder="请输入任务名称"
                  />
                </div>

                <div>
                  <Label htmlFor="description">任务描述</Label>
                  <Textarea
                    id="description"
                    value={taskData.description}
                    onChange={(e) => setTaskData(prev => ({ ...prev, description: e.target.value }))}
                    placeholder="请输入任务描述"
                    rows={3}
                  />
                </div>

                <div>
                  <Label htmlFor="type">任务类型 *</Label>
                  <Select value={taskData.type} onValueChange={(value) => setTaskData(prev => ({ ...prev, type: value }))}>
                    <SelectTrigger>
                      <SelectValue placeholder="请选择任务类型" />
                    </SelectTrigger>
                    <SelectContent>
                      {taskTypes.map(type => (
                        <SelectItem key={type.value} value={type.value}>
                          {type.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="flex items-center space-x-2">
                  <Switch
                    id="enabled"
                    checked={taskData.enabled}
                    onCheckedChange={(checked) => setTaskData(prev => ({ ...prev, enabled: checked }))}
                  />
                  <Label htmlFor="enabled">启用任务</Label>
                </div>
              </CardContent>
            </Card>

            {/* 执行计划 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Clock className="w-5 h-5" />
                  <span>执行计划</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label>计划类型</Label>
                  <Select 
                    value={taskData.schedule.type} 
                    onValueChange={(value) => setTaskData(prev => ({ 
                      ...prev, 
                      schedule: { ...prev.schedule, type: value }
                    }))}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="cron">Cron 表达式</SelectItem>
                      <SelectItem value="interval">固定间隔</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {taskData.schedule.type === 'cron' ? (
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="cronExpression">Cron 表达式 *</Label>
                      <Input
                        id="cronExpression"
                        value={taskData.schedule.cronExpression}
                        onChange={(e) => setTaskData(prev => ({ 
                          ...prev, 
                          schedule: { ...prev.schedule, cronExpression: e.target.value }
                        }))}
                        placeholder="例如: 0 2 * * * (每日凌晨2点)"
                      />
                    </div>

                    <div>
                      <Label>常用预设</Label>
                      <Select 
                        value={taskData.schedule.cronExpression}
                        onValueChange={(value) => setTaskData(prev => ({ 
                          ...prev, 
                          schedule: { ...prev.schedule, cronExpression: value }
                        }))}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="选择预设时间" />
                        </SelectTrigger>
                        <SelectContent>
                          {cronPresets.map(preset => (
                            <SelectItem key={preset.value} value={preset.value}>
                              {preset.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="intervalValue">间隔数值</Label>
                      <Input
                        id="intervalValue"
                        type="number"
                        min="1"
                        value={taskData.schedule.intervalValue}
                        onChange={(e) => setTaskData(prev => ({ 
                          ...prev, 
                          schedule: { ...prev.schedule, intervalValue: parseInt(e.target.value) || 1 }
                        }))}
                      />
                    </div>
                    <div>
                      <Label htmlFor="intervalUnit">时间单位</Label>
                      <Select 
                        value={taskData.schedule.intervalUnit}
                        onValueChange={(value) => setTaskData(prev => ({ 
                          ...prev, 
                          schedule: { ...prev.schedule, intervalUnit: value }
                        }))}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {intervalUnits.map(unit => (
                            <SelectItem key={unit.value} value={unit.value}>
                              {unit.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 脚本配置 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Code className="w-5 h-5" />
                  <span>脚本配置</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="script">执行脚本</Label>
                  <Textarea
                    id="script"
                    value={taskData.script}
                    onChange={(e) => setTaskData(prev => ({ ...prev, script: e.target.value }))}
                    placeholder="请输入要执行的脚本或命令"
                    rows={8}
                    className="font-mono text-sm"
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="timeout">超时时间 (秒)</Label>
                    <Input
                      id="timeout"
                      type="number"
                      min="1"
                      value={taskData.timeout}
                      onChange={(e) => setTaskData(prev => ({ ...prev, timeout: parseInt(e.target.value) || 300 }))}
                    />
                  </div>
                  <div>
                    <Label htmlFor="retryCount">重试次数</Label>
                    <Input
                      id="retryCount"
                      type="number"
                      min="0"
                      max="10"
                      value={taskData.retryCount}
                      onChange={(e) => setTaskData(prev => ({ ...prev, retryCount: parseInt(e.target.value) || 0 }))}
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 右侧：通知设置和帮助 */}
          <div className="space-y-6">
            {/* 通知设置 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <AlertCircle className="w-5 h-5" />
                  <span>通知设置</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <Label htmlFor="notifyOnSuccess">成功通知</Label>
                    <p className="text-sm text-material-grey-600">任务执行成功时发送通知</p>
                  </div>
                  <Switch
                    id="notifyOnSuccess"
                    checked={taskData.notifyOnSuccess}
                    onCheckedChange={(checked) => setTaskData(prev => ({ ...prev, notifyOnSuccess: checked }))}
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div>
                    <Label htmlFor="notifyOnFailure">失败通知</Label>
                    <p className="text-sm text-material-grey-600">任务执行失败时发送通知</p>
                  </div>
                  <Switch
                    id="notifyOnFailure"
                    checked={taskData.notifyOnFailure}
                    onCheckedChange={(checked) => setTaskData(prev => ({ ...prev, notifyOnFailure: checked }))}
                  />
                </div>

                <div>
                  <Label htmlFor="notifyEmail">通知邮箱</Label>
                  <Input
                    id="notifyEmail"
                    type="email"
                    value={taskData.notifyEmail}
                    onChange={(e) => setTaskData(prev => ({ ...prev, notifyEmail: e.target.value }))}
                    placeholder="请输入邮箱地址"
                  />
                </div>
              </CardContent>
            </Card>

            {/* Cron 表达式帮助 */}
            <Card>
              <CardHeader>
                <CardTitle>Cron 表达式说明</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3 text-sm">
                  <div>
                    <p className="font-medium text-material-grey-800">格式：分 时 日 月 周</p>
                  </div>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-material-grey-600">*</span>
                      <span className="text-material-grey-800">任意值</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-material-grey-600">*/5</span>
                      <span className="text-material-grey-800">每5个单位</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-material-grey-600">1-5</span>
                      <span className="text-material-grey-800">范围值</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-material-grey-600">1,3,5</span>
                      <span className="text-material-grey-800">列表值</span>
                    </div>
                  </div>
                  <div className="pt-2 border-t border-material-grey-200">
                    <p className="text-xs text-material-grey-500">
                      示例：0 2 * * * 表示每日凌晨2点执行
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 任务类型说明 */}
            <Card>
              <CardHeader>
                <CardTitle>任务类型说明</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3 text-sm">
                  <div>
                    <p className="font-medium text-material-grey-800">数据备份</p>
                    <p className="text-material-grey-600">定期备份数据库或文件</p>
                  </div>
                  <div>
                    <p className="font-medium text-material-grey-800">文件清理</p>
                    <p className="text-material-grey-600">清理临时文件和缓存</p>
                  </div>
                  <div>
                    <p className="font-medium text-material-grey-800">报告生成</p>
                    <p className="text-material-grey-600">生成统计报告</p>
                  </div>
                  <div>
                    <p className="font-medium text-material-grey-800">系统监控</p>
                    <p className="text-material-grey-600">监控系统状态</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </>
  );
};

export default TaskCreate;
